//
//  RunningMachineDataModel.swift
//  TimeBoat
//
//  Created by Jun on 2022/9/8.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import Foundation

/// 跑步机
@objcMembers class RunningMachineDataModel: NSObject {
    /// 所用时间 4Byte (单位:秒)
    var useTime: UInt32 = 0

    /// 总计步数 4Byte
    var stepCount: UInt32 = 0

    /// 卡路里 4Byte （cal）
    var calorie: UInt32 = 0

    /// 步频数组 uint16[]（步数每分钟，运动过程中，每一分钟记录一个数据）
    var stepFrequencyList: [UInt16]? = nil

    /// 心率数组 uint8 [ ] (单位:次/分钟，每 5 分钟记录一次数据)
    var heartRateList: [UInt8]? = nil
    
    
    convenience init(buf: [UInt8]) {
        self.init()
        
        var index = 0
        
        if (index + 4 <= buf.count) {
            // 所用时间 4Byte (单位:秒)
            useTime = UInt32.toUInt32(buf: buf, offset: index)
            index += 4
        }

        if (index + 4 <= buf.count) {
            // 总计步数 4Byte
            stepCount = UInt32.toUInt32(buf: buf, offset: index)
            index += 4
        }

        if (index + 4 <= buf.count) {
            // 卡路里 4Byte （cal）
            calorie = UInt32.toUInt32(buf: buf, offset: index)
            index += 4
        }

        if (index + 2 <= buf.count) {
            // 步频数组 uint16[]（步数每分钟，运动过程中，每一分钟记录一个数据）
            let walkRateLength = Int(UInt16.toUInt16(buf: buf, offset: index))
            index += 2;

            if (walkRateLength > 0) {
                if (index + walkRateLength * 2 <= buf.count) {
                    stepFrequencyList = [UInt16]()
                    for _ in 0...(walkRateLength-1) {
                        let data = UInt16.toUInt16(buf: buf, offset: index)
                        index += 2
                        stepFrequencyList?.append(data)
                    }
                } else {
                    Log.debug("index + walkRateLength * 2 is overflow, \(index), \(walkRateLength)")
                }
            }
        }

        if (index + 2 <= buf.count) {
            // 心率数组 uint8[] (单位:次/分钟，每 5 分钟记录一次数据)
            let heartRateLength = Int(UInt16.toUInt16(buf: buf, offset: index))
            index += 2

            if (heartRateLength > 0) {
                if (index + heartRateLength <= buf.count) {
                    heartRateList = Array<UInt8>.copyBuffer(buffer: buf, offset: index, length: heartRateLength)
                } else {
                    Log.debug("index + heartRateLength is overflow, \(index), \(heartRateLength)")
                }
            }
        }
    }
    
    @objc func toString() -> String {
        var str = self.yy_modelToJSONString()
        if nil == str {
            str = ""
        }
        
        return str!
    }
}
